package com.example.managemyself.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import javax.net.ssl.SSLException;

/**
 * 网络工具类
 * 提供网络状态检查、错误处理和重试机制
 */
public class NetworkUtils {
    
    private static final String TAG = "NetworkUtils";
    
    /**
     * 检查网络连接状态
     */
    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager connectivityManager = 
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            
            if (connectivityManager != null) {
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                return activeNetworkInfo != null && activeNetworkInfo.isConnected();
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking network availability", e);
        }
        return false;
    }
    
    /**
     * 检查WiFi连接状态
     */
    public static boolean isWifiConnected(Context context) {
        try {
            ConnectivityManager connectivityManager = 
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            
            if (connectivityManager != null) {
                NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                return wifiInfo != null && wifiInfo.isConnected();
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking WiFi connectivity", e);
        }
        return false;
    }
    
    /**
     * 检查移动数据连接状态
     */
    public static boolean isMobileDataConnected(Context context) {
        try {
            ConnectivityManager connectivityManager = 
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            
            if (connectivityManager != null) {
                NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                return mobileInfo != null && mobileInfo.isConnected();
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking mobile data connectivity", e);
        }
        return false;
    }
    
    /**
     * 获取网络类型描述
     */
    public static String getNetworkTypeDescription(Context context) {
        try {
            ConnectivityManager connectivityManager = 
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            
            if (connectivityManager != null) {
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
                    switch (activeNetworkInfo.getType()) {
                        case ConnectivityManager.TYPE_WIFI:
                            return "WiFi";
                        case ConnectivityManager.TYPE_MOBILE:
                            return "移动数据";
                        case ConnectivityManager.TYPE_ETHERNET:
                            return "以太网";
                        default:
                            return "其他网络";
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting network type", e);
        }
        return "无网络连接";
    }
    
    /**
     * 获取友好的网络错误信息
     */
    public static String getNetworkErrorMessage(Throwable throwable) {
        if (throwable == null) {
            return "未知网络错误";
        }
        
        if (throwable instanceof SocketTimeoutException) {
            return "网络连接超时，请检查网络连接后重试";
        } else if (throwable instanceof ConnectException) {
            return "无法连接到服务器，请检查网络设置";
        } else if (throwable instanceof UnknownHostException) {
            return "网络不可用，请检查网络连接";
        } else if (throwable instanceof SSLException) {
            return "安全连接失败，请检查网络安全设置";
        } else if (throwable instanceof TimeoutException) {
            return "请求超时，请稍后重试";
        } else if (throwable.getMessage() != null) {
            String message = throwable.getMessage().toLowerCase();
            if (message.contains("timeout")) {
                return "网络请求超时，请检查网络连接";
            } else if (message.contains("connection")) {
                return "网络连接失败，请检查网络设置";
            } else if (message.contains("host")) {
                return "无法找到服务器，请检查网络连接";
            }
        }
        
        return "网络请求失败: " + throwable.getMessage();
    }
    
    /**
     * 网络错误类型枚举
     */
    public enum NetworkErrorType {
        TIMEOUT,        // 超时
        CONNECTION,     // 连接失败
        NO_NETWORK,     // 无网络
        SSL_ERROR,      // SSL错误
        SERVER_ERROR,   // 服务器错误
        UNKNOWN         // 未知错误
    }
    
    /**
     * 分析网络错误类型
     */
    public static NetworkErrorType analyzeNetworkError(Throwable throwable) {
        if (throwable == null) {
            return NetworkErrorType.UNKNOWN;
        }
        
        if (throwable instanceof SocketTimeoutException || throwable instanceof TimeoutException) {
            return NetworkErrorType.TIMEOUT;
        } else if (throwable instanceof ConnectException) {
            return NetworkErrorType.CONNECTION;
        } else if (throwable instanceof UnknownHostException) {
            return NetworkErrorType.NO_NETWORK;
        } else if (throwable instanceof SSLException) {
            return NetworkErrorType.SSL_ERROR;
        } else {
            return NetworkErrorType.UNKNOWN;
        }
    }
    
    /**
     * 根据错误类型获取建议的重试次数
     */
    public static int getRecommendedRetryCount(NetworkErrorType errorType) {
        switch (errorType) {
            case TIMEOUT:
                return 3; // 超时错误重试3次
            case CONNECTION:
                return 2; // 连接错误重试2次
            case NO_NETWORK:
                return 1; // 无网络只重试1次
            case SSL_ERROR:
                return 1; // SSL错误重试1次
            case SERVER_ERROR:
                return 2; // 服务器错误重试2次
            default:
                return 1; // 未知错误重试1次
        }
    }
    
    /**
     * 根据错误类型获取建议的重试延迟时间（毫秒）
     */
    public static long getRecommendedRetryDelay(NetworkErrorType errorType) {
        switch (errorType) {
            case TIMEOUT:
                return 3000; // 超时错误延迟3秒
            case CONNECTION:
                return 2000; // 连接错误延迟2秒
            case NO_NETWORK:
                return 5000; // 无网络延迟5秒
            case SSL_ERROR:
                return 1000; // SSL错误延迟1秒
            case SERVER_ERROR:
                return 2000; // 服务器错误延迟2秒
            default:
                return 2000; // 未知错误延迟2秒
        }
    }
    
    /**
     * 网络状态监听接口
     */
    public interface NetworkStatusListener {
        void onNetworkAvailable();
        void onNetworkUnavailable();
    }
} 